﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;

namespace Qy.Web.Authorize
{
    /// <summary>
    /// JWT授权校验访问
    /// 如果跳过授权登录在Action 或controller加上 AllowAnonymousAttribute
    /// </summary>
    public class VerifyAttribute : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// 判断token是否正确
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var noNeedCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
            }
            if (noNeedCheck) return;
            if (JwtHelper.GetLoginUser() == null)
            {
                string url = context.HttpContext.Request.Path;
                string msg = $"请求访问[{url}]失败，无法访问系统资源";
                JsonResult result = new(new { status = 401, msg})
                {
                    ContentType = "application/json",
                };
                context.Result = result;
            }
        }
    }
}
